package com.lcq.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.lcq.gulimall.product.vo.IndexCategory2Vo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lcq.common.utils.PageUtils;
import com.lcq.common.utils.Query;

import com.lcq.gulimall.product.dao.CategoryDao;
import com.lcq.gulimall.product.entity.CategoryEntity;
import com.lcq.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    private List<CategoryEntity> categoryEntities = null;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public Long[] findCateLogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        paths = findParentPath(catelogId, paths);
        // 收集的时候是顺序 前端是逆序显示的 所以用集合工具类给它逆序一下
        Collections.reverse(paths);
        return paths.toArray(new Long[paths.size()]);
    }

    @Override
    @Cacheable(value = "category",key = "'categoryLevel1'")
    public List<CategoryEntity> getCategoriesByLevel(Integer level) {
        if (level==null || level==0){
            return null;
        }
        return this.getBaseMapper().selectList(new QueryWrapper<CategoryEntity>().eq("cat_level",level));
    }

    public List<CategoryEntity> getCategoriesByLevelOp(Long parentCid) {
        return categoryEntities.stream().filter(e->{
            return e.getParentCid()==parentCid;
        }).collect(Collectors.toList());
    }

    public List<IndexCategory2Vo> getCategory2List(Long catalog1Id) {
        if (catalog1Id==null || catalog1Id==0){
            return null;
        }

        List<CategoryEntity> category2EntityList = this.getBaseMapper().selectList(
                new QueryWrapper<CategoryEntity>().eq("parent_cid",catalog1Id));
        if(category2EntityList==null||category2EntityList.size()<=0){
            return null;
        }

        List<IndexCategory2Vo> category2List = category2EntityList.stream().map(e -> {
            IndexCategory2Vo c2Vo = new IndexCategory2Vo();
            c2Vo.setCatalog1Id(e.getParentCid());
            c2Vo.setId(e.getCatId());
            c2Vo.setName(e.getName());
            List<CategoryEntity> category3EntityList = this.getBaseMapper().selectList(
                    new QueryWrapper<CategoryEntity>().eq("parent_cid",e.getParentCid()));
            if(category2EntityList!=null&&category2EntityList.size()>0){
                List<IndexCategory2Vo.Catalog3> category3List = category3EntityList.stream().map(e3 -> {
                    IndexCategory2Vo.Catalog3 c3Vo = new IndexCategory2Vo.Catalog3();
                    c3Vo.setCatalog2Id(e3.getParentCid());
                    c3Vo.setId(e3.getCatId());
                    c3Vo.setName(e3.getName());
                    return c3Vo;
                }).collect(Collectors.toList());
                c2Vo.setCatalog3List(category3List);
            }
            return c2Vo;
        }).collect(Collectors.toList());

        return category2List;
    }

    public List<IndexCategory2Vo> getCategory2ListOp(Long catalog1Id) {
        if (catalog1Id==null || catalog1Id==0){
            return null;
        }

        List<CategoryEntity> category2EntityList = getCategoriesByLevelOp(catalog1Id);
        if(category2EntityList==null||category2EntityList.size()<=0){
            return null;
        }

        List<IndexCategory2Vo> category2List = category2EntityList.stream().map(e -> {
            IndexCategory2Vo c2Vo = new IndexCategory2Vo();
            c2Vo.setCatalog1Id(e.getParentCid());
            c2Vo.setId(e.getCatId());
            c2Vo.setName(e.getName());
            List<CategoryEntity> category3EntityList = getCategoriesByLevelOp(e.getCatId());
            if(category2EntityList!=null&&category2EntityList.size()>0){
                List<IndexCategory2Vo.Catalog3> category3List = category3EntityList.stream().map(e3 -> {
                    IndexCategory2Vo.Catalog3 c3Vo = new IndexCategory2Vo.Catalog3();
                    c3Vo.setCatalog2Id(e3.getParentCid());
                    c3Vo.setId(e3.getCatId());
                    c3Vo.setName(e3.getName());
                    return c3Vo;
                }).collect(Collectors.toList());
                c2Vo.setCatalog3List(category3List);
            }
            return c2Vo;
        }).collect(Collectors.toList());

        return category2List;
    }

    @Override
    public Map getCatalogJson() {
        List<CategoryEntity> entities = getCategoriesByLevel(1);
        if(entities==null&&entities.size()<=0){
            return null;
        }

        Map<String, List<IndexCategory2Vo>> map = entities.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            return getCategory2List(v.getCatId());
        }));

        return map;
    }

    /**
     * 优化
     * */
    @Override
    public Map getCatalogJsonOp(){
        if(categoryEntities==null){
            categoryEntities = this.getBaseMapper().selectList(null);
        }
        List<CategoryEntity> entities = getCategoriesByLevelOp(0L);
        if(entities==null&&entities.size()<=0){
            return null;
        }
        Map<String, List<IndexCategory2Vo>> map = entities.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            return getCategory2ListOp(v.getCatId());
        }));
        return map;
    }
    /**
     * 优化  使用redis
     * */
    public List<CategoryEntity> getCategoriesByLevelRedis(Long parentCid, List<CategoryEntity> entities) {
        if(entities==null||entities.size()==0){
            return null;
        }
        return entities.stream().filter(e->{
            return e.getParentCid()==parentCid;
        }).collect(Collectors.toList());
    }

    public List<IndexCategory2Vo> getCategory2ListRedis(Long catalog1Id, List<CategoryEntity> entities) {
        if (catalog1Id==null || catalog1Id==0){
            return null;
        }

        List<CategoryEntity> category2EntityList = getCategoriesByLevelRedis(catalog1Id, entities);
        if(category2EntityList==null||category2EntityList.size()<=0){
            return null;
        }

        List<IndexCategory2Vo> category2List = category2EntityList.stream().map(e -> {
            IndexCategory2Vo c2Vo = new IndexCategory2Vo();
            c2Vo.setCatalog1Id(e.getParentCid());
            c2Vo.setId(e.getCatId());
            c2Vo.setName(e.getName());
            List<CategoryEntity> category3EntityList = getCategoriesByLevelRedis(e.getCatId(), entities);
            if(category2EntityList!=null&&category2EntityList.size()>0){
                List<IndexCategory2Vo.Catalog3> category3List = category3EntityList.stream().map(e3 -> {
                    IndexCategory2Vo.Catalog3 c3Vo = new IndexCategory2Vo.Catalog3();
                    c3Vo.setCatalog2Id(e3.getParentCid());
                    c3Vo.setId(e3.getCatId());
                    c3Vo.setName(e3.getName());
                    return c3Vo;
                }).collect(Collectors.toList());
                c2Vo.setCatalog3List(category3List);
            }
            return c2Vo;
        }).collect(Collectors.toList());

        return category2List;
    }


    public String createCatalogJson(){
        String categoryEntitiesStr = stringRedisTemplate.opsForValue().get("categoryEntities");
        List<CategoryEntity> categoryEntitiesRedis = null;
        if(categoryEntitiesStr==null){
            categoryEntitiesRedis = this.getBaseMapper().selectList(null);
            stringRedisTemplate.opsForValue().set("categoryEntities",JSON.toJSONString(categoryEntitiesRedis));
        }else {
            categoryEntitiesRedis = JSON.parseObject(categoryEntitiesStr, new TypeReference<List<CategoryEntity>>(){});
        }

        List<CategoryEntity> entities = getCategoriesByLevelRedis(0L,categoryEntitiesRedis);
        if(entities==null||entities.size()<=0){
            return null;
        }

        List<CategoryEntity> finalCategoryEntitiesRedis = categoryEntitiesRedis;
        Map<String, List<IndexCategory2Vo>> map = entities.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            return getCategory2ListRedis(v.getCatId(), finalCategoryEntitiesRedis);
        }));
        String categoryJsonStr = JSON.toJSONString(map);
        stringRedisTemplate.opsForValue().set("catalogJson",categoryJsonStr);
        return categoryJsonStr;
    }

    @Override
    public String getCatalogJsonRedis(){
        while(true){
            String categoryJsonStr = stringRedisTemplate.opsForValue().get("catalogJson");
            Map<String, List<IndexCategory2Vo>> mapRes = null;
            if(categoryJsonStr!=null){
                return categoryJsonStr;
            }
            String uuid = UUID.randomUUID().toString();
            Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid, 30, TimeUnit.SECONDS);
            if(lock){
                String res = createCatalogJson();
                String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                stringRedisTemplate.execute(new DefaultRedisScript<>(script,Long.class),Arrays.asList("lock"),uuid);
                return res;
            }else {
                try {
                    TimeUnit.MILLISECONDS.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 递归收集所有节点
     */
    private List<Long> findParentPath(Long catlogId, List<Long> paths) {
        // 1、收集当前节点id
        paths.add(catlogId);
        CategoryEntity byId = this.getById(catlogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }
    @Override
    public List<CategoryEntity> queryCategoryTree() {
        List<CategoryEntity> all = this.getBaseMapper().selectList(null);
        List<CategoryEntity> list = all.stream()
                .filter((entity)->(entity.getCatLevel()==null?0:entity.getCatLevel())==1)
                .map(entity -> {
                    entity.setChildren(getChildren(entity,all));
                    return entity;
                }).collect(Collectors.toList());

        return list;
    }

    public List<CategoryEntity> getChildren(CategoryEntity parent, List<CategoryEntity> all){
        return all.stream()
                .filter((entity)->(entity.getParentCid()==null?0:entity.getParentCid())==parent.getCatId())
                .map(entity -> {
                    entity.setChildren(getChildren(entity,all));
                    return entity;
                }).collect(Collectors.toList());
    }
}